package com.zit.service;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.zit.dao.BaseDAO;
import com.zit.service.db.HibernateSessionFactory;

public class BaseService {

	protected BaseDAO baseDAO = new BaseDAO();
	
	protected Session getSession(){
		return HibernateSessionFactory.getSession();
	}
	
	public void save(Object obj) {
		Session s = null;
		Transaction tx = null ;
		try {
			s = getSession();
			tx = s.beginTransaction();
			baseDAO.save(obj,s);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			s.close();
		}
	}

	public void update(Object obj) {
		Session s = null;
		Transaction tx = null ;
		try {
			s = getSession();
			tx = s.beginTransaction();
			baseDAO.update(obj,s);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			s.close();
		}
	}

	public void delete(Object obj) {
		Session s = null;
		Transaction tx = null ;
		try {
			s = getSession();
			tx = s.beginTransaction();
			baseDAO.delete(obj,s);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			s.close();
		}
	}

	public Object findById(Class<?> clazz, Serializable id) {
		Session s = null;
		Transaction tx = null ;
		Object o = null ;
		try {
			s = getSession();
			tx = s.beginTransaction();
			o = baseDAO.findById(clazz,id,s);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			s.close();
		}
		return o ;
	}

	public List findAll(Class<?> clazz) {
		Session s = null;
		Transaction tx = null ;
		List list = null ;
		try {
			s = getSession();
			tx = s.beginTransaction();
			list = baseDAO.findAll(clazz,s);
			tx.commit();
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			s.close();
		}
		return list ;
	}
}
